package com.fcy.teamwork.business.login

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import cn.jpush.im.android.api.JMessageClient
import cn.jpush.im.api.BasicCallback
import com.fcy.teamwork.App
import com.fcy.teamwork.pojo.Person
import com.fcy.teamwork.repo.RetrofitClient
import com.fcy.teamwork.repo.service.SystemService
import com.google.gson.Gson
import com.google.gson.JsonObject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.selects.select
import org.json.JSONObject
import kotlin.coroutines.resume
import kotlin.coroutines.suspendCoroutine

class LoginVM : ViewModel() {
    private val service by lazy {
        RetrofitClient.getService<SystemService>()
    }

    suspend fun login(userName: String, pwd: String): Boolean = suspendCoroutine {
        if (!checkFormat(userName, pwd)) {
            it.resume(false)
            return@suspendCoroutine
        }
        viewModelScope.launch {
            val jm = async(context = Dispatchers.IO) { loginJM(userName, pwd) }
            val teamwork = async(context = Dispatchers.IO) {
                loginTeamWork(userName, pwd)
            }
            if (jm.await() && teamwork.await()) {
                it.resume(true)
            } else it.resume(false)
        }
    }

    private suspend fun loginTeamWork(uName: String, pwd1: String): Boolean {
        service.login(Person().apply {
            personId = uName
            pwd = pwd1
        }).also { result ->
            return if (result.isOk) {
                RetrofitClient.token =
                    result.data["token"] as? String
                        ?: throw IllegalStateException("登陆成功，token解析失败")
                App.person =
                    Gson().fromJson(result.data["personInfo"] as? String, Person::class.java)
                        ?: throw IllegalArgumentException("登录成功，用户信息解析失败")
                true
            } else {
                false
            }
        }
    }

    private suspend fun loginJM(userName: String, pwd: String) = suspendCoroutine {
        JMessageClient.login(userName, pwd, object : BasicCallback() {
            override fun gotResult(p0: Int, p1: String?) {
                if (p0 == 0) {
                    it.resume(true)
                } else {
                    it.resume(false)
                }
            }
        })
    }

    private fun checkFormat(userName: String, pwd: String): Boolean {
        if (userName.isBlank() || pwd.isBlank()) {
            return false
        }
        return true
    }
}